// 记忆翻牌游戏类
class MemoryGame {
    constructor() {
        this.boardElement = document.getElementById('memory-board');
        
        this.difficulties = {
            easy: { size: 4, pairs: 8 },
            medium: { size: 6, pairs: 18 },
            hard: { size: 8, pairs: 32 }
        };
        
        this.currentDifficulty = 'easy';
        this.cards = [];
        this.flippedCards = [];
        this.matchedPairs = 0;
        this.moves = 0;
        this.startTime = 0;
        this.timer = null;
        this.isGameRunning = false;
        
        // 卡片图案
        this.symbols = ['🐶', '🐱', '🐭', '🐹', '🐰', '🦊', '🐻', '🐼', 
                       '🐨', '🐯', '🦁', '🐮', '🐷', '🐸', '🐵', '🐔',
                       '🐧', '🐦', '🐤', '🦆', '🦅', '🦉', '🦇', '🐺',
                       '🐗', '🐴', '🦄', '🐝', '🐛', '🦋', '🐌', '🐞'];
        
        this.bindEvents();
        this.loadAndDisplayGameData();
    }

    // 初始化游戏
    initGame() {
        const config = this.difficulties[this.currentDifficulty];
        this.cards = [];
        this.flippedCards = [];
        this.matchedPairs = 0;
        this.moves = 0;
        this.isGameRunning = false;
        
        // 创建卡片对
        const selectedSymbols = this.symbols.slice(0, config.pairs);
        const cardSymbols = [...selectedSymbols, ...selectedSymbols];
        
        // 打乱卡片
        for (let i = cardSymbols.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [cardSymbols[i], cardSymbols[j]] = [cardSymbols[j], cardSymbols[i]];
        }
        
        // 创建卡片对象
        cardSymbols.forEach((symbol, index) => {
            this.cards.push({
                id: index,
                symbol: symbol,
                isFlipped: false,
                isMatched: false
            });
        });
        
        this.updateMoves();
        this.createBoardHTML();
    }

    // 创建游戏板HTML
    createBoardHTML() {
        const config = this.difficulties[this.currentDifficulty];
        this.boardElement.innerHTML = '';
        this.boardElement.style.gridTemplateColumns = `repeat(${config.size}, 1fr)`;
        this.boardElement.style.gridTemplateRows = `repeat(${config.size}, 1fr)`;
        
        // 根据难度调整卡片大小
        const cardSize = config.size === 4 ? '70px' : config.size === 6 ? '55px' : '45px';
        this.boardElement.style.width = `${config.size * (parseInt(cardSize) + 8)}px`;
        this.boardElement.style.height = `${config.size * (parseInt(cardSize) + 8)}px`;
        
        this.cards.forEach(card => {
            const cardElement = document.createElement('div');
            cardElement.className = 'memory-card';
            cardElement.dataset.id = card.id;
            cardElement.style.width = cardSize;
            cardElement.style.height = cardSize;
            
            cardElement.innerHTML = `
                <div class="card-inner">
                    <div class="card-front">?</div>
                    <div class="card-back">${card.symbol}</div>
                </div>
            `;
            
            cardElement.addEventListener('click', () => this.flipCard(card.id));
            this.boardElement.appendChild(cardElement);
        });
    }

    // 开始游戏
    async startGame() {
        this.initGame();
        await this.updateGameStats();
        this.resetTimer();
    }

    // 翻牌
    flipCard(cardId) {
        const card = this.cards[cardId];
        
        if (!this.isGameRunning) {
            this.isGameRunning = true;
            this.startTimer();
        }
        
        if (card.isFlipped || card.isMatched || this.flippedCards.length >= 2) {
            return;
        }
        
        card.isFlipped = true;
        this.flippedCards.push(card);
        this.updateCardDisplay(cardId);
        
        if (this.flippedCards.length === 2) {
            this.moves++;
            this.updateMoves();
            
            setTimeout(() => {
                this.checkMatch();
            }, 1000);
        }
    }

    // 检查匹配
    checkMatch() {
        const [card1, card2] = this.flippedCards;
        
        if (card1.symbol === card2.symbol) {
            // 匹配成功
            card1.isMatched = true;
            card2.isMatched = true;
            this.matchedPairs++;
            
            this.updateCardDisplay(card1.id);
            this.updateCardDisplay(card2.id);
            
            // 检查游戏是否完成
            if (this.matchedPairs === this.difficulties[this.currentDifficulty].pairs) {
                this.gameComplete();
            }
        } else {
            // 匹配失败，翻回去
            card1.isFlipped = false;
            card2.isFlipped = false;
            
            this.updateCardDisplay(card1.id);
            this.updateCardDisplay(card2.id);
        }
        
        this.flippedCards = [];
    }

    // 更新卡片显示
    updateCardDisplay(cardId) {
        const card = this.cards[cardId];
        const cardElement = this.boardElement.querySelector(`[data-id="${cardId}"]`);
        
        if (card.isMatched) {
            cardElement.classList.add('matched');
        } else if (card.isFlipped) {
            cardElement.classList.add('flipped');
        } else {
            cardElement.classList.remove('flipped');
        }
    }

    // 游戏完成
    async gameComplete() {
        this.isGameRunning = false;
        this.stopTimer();
        
        const time = Math.floor((Date.now() - this.startTime) / 1000);
        await this.saveGameData(time);
        
        alert(`恭喜完成！\n用时: ${time}秒\n步数: ${this.moves}`);
    }

    // 开始计时
    startTimer() {
        this.startTime = Date.now();
        this.timer = setInterval(() => {
            const elapsed = Math.floor((Date.now() - this.startTime) / 1000);
            document.getElementById('memory-time').textContent = elapsed;
        }, 1000);
    }

    // 停止计时
    stopTimer() {
        if (this.timer) {
            clearInterval(this.timer);
            this.timer = null;
        }
    }

    // 重置计时器
    resetTimer() {
        this.stopTimer();
        document.getElementById('memory-time').textContent = '0';
    }

    // 更新步数显示
    updateMoves() {
        document.getElementById('memory-moves').textContent = this.moves;
    }

    // 绑定事件
    bindEvents() {
        // 难度选择
        document.querySelectorAll('#memory-game .difficulty-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                document.querySelectorAll('#memory-game .difficulty-btn').forEach(b => 
                    b.classList.remove('active'));
                btn.classList.add('active');
                this.currentDifficulty = btn.dataset.difficulty;
                this.startGame();
            });
        });
    }

    // 保存游戏数据
    async saveGameData(time) {
        const currentData = await this.loadGameData();
        const difficultyKey = `bestTime_${this.currentDifficulty}`;
        const gameData = {
            ...currentData,
            [difficultyKey]: Math.min(time, currentData[difficultyKey] || Infinity),
            gamesPlayed: (currentData.gamesPlayed || 0) + 1,
            gamesCompleted: (currentData.gamesCompleted || 0) + 1
        };
        await authManager.saveGameData('memory', gameData);
        await this.updateGameStats();
    }

    // 加载游戏数据
    async loadGameData() {
        return await authManager.loadGameData('memory') || {};
    }

    // 更新游戏统计显示
    async updateGameStats() {
        const data = await this.loadGameData();
        const difficultyKey = `bestTime_${this.currentDifficulty}`;
        const bestTime = data[difficultyKey];
        document.getElementById('memory-best-time').textContent = 
            bestTime && bestTime !== Infinity ? `${bestTime}s` : '--';
    }

    // 加载并显示游戏数据
    async loadAndDisplayGameData() {
        await this.updateGameStats();
    }
}

// 创建游戏实例
let memoryGame;